#!/usr/bin/env python
# @author: Samuel Taylor <samtaylor.uk@gmail.com>
# @package: winecellar
# @license: GNU GPLv3
#
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010  Samuel Taylor <samtaylor.uk@gmail.com>
#----------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------

__author__ = 'Samuel Taylor <samtaylor.uk@gmail.com>'

import os
import logging
import tarfile

logger = logging.getLogger('build_wine')
hdlr = logging.FileHandler('build_wine.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

def cleanup(cwd):
    os.system("rm -fR /tmp/build_wine /tmp/wine*")
    os.chdir(cwd)

for filename in os.listdir('todo'):
    basename, extension = os.path.splitext(filename)
    if extension == ".bz2":
        basename, extension2 = os.path.splitext(basename)
        version = basename.split("wine-")
        
        logger.info("Building Wine Version "+version[1])
        logger.debug("Filename: "+filename)
        print "Building Wine Version "+version[1]
        
        logger.info("Extracting version: "+version[1])
        print "Extracting version: "+version[1]
        cwd = os.getcwd()
        os.chdir("/tmp")
        try:
            tar = tarfile.open(cwd+"/todo/"+filename, "r")
	    files = tar.getmembers()
	    for item in files:
        	tar.extract(item)
        except:
            logger.error("Unable to extract version: "+version[1])
            print "Unable to extract version: "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/failed/"+filename)
            cleanup(cwd)
            continue
        os.chdir("/tmp/"+basename)

        logger.info("Building temp package build folder for "+version[1])
        print "Building temp package build folder for "+version[1]
        os.makedirs("/tmp/build_wine/data")

        logger.info("Running configure for "+version[1])
        print "Running configure for "+version[1]
        code = os.system("./configure --prefix=/tmp/build_wine/data")
        if code != 0:
            logger.error("Failed configure for "+version[1])
            print "Failed configure for "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/failed/"+filename)
            cleanup(cwd)
            continue
        else:
            logger.info("Configure finished for "+version[1])
            print "Configure finished for "+version[1]
        
        logger.info("Running make depend for "+version[1])
        print "Running make depend for "+version[1]
        code = os.system("make depend -j2")
        if code != 0:
            logger.error("Failed make depend for "+version[1])
            print "Failed make depend for "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/failed/"+filename)
            cleanup(cwd)
            continue
        else:
            logger.info("make depend finished for "+version[1])
            print "make depend finished for "+version[1]

        logger.info("Running make for "+version[1])
        print "Running make for "+version[1]
        code = os.system("make -j2")
        if code != 0:
            logger.error("Failed make for "+version[1])
            print "Failed make for "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/failed/"+filename)
            cleanup(cwd)
            continue
        else:
            logger.info("make finished for "+version[1])
            print "make finished for "+version[1]
            
        logger.info("Running make install for "+version[1])
        print "Running make install for "+version[1]
        code = os.system("make install -j2")
        if code != 0:
            logger.error("Failed make install for "+version[1])
            print "Failed make install for "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/failed/"+filename)
            cleanup(cwd)
            continue
        else:
            logger.info("make install finished for "+version[1])
            print "make install finished for "+version[1]
            
        os.chdir("/tmp/build_wine")

        logger.info("Writing control.xml for "+version[1])
        print "Writing control.xml for "+version[1]
        try:
            file = open("control.xml", 'w')
            file.write("<?xml version='1.0' encoding='iso-8859-1'?>\n<Wine version=\"0.1\">\n  <name>wine</name>\n  <version>"+version[1]+"</version>\n  <license name=\"GNU LGPL\">http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</license>\n  <vendor>Wine HQ</vendor>\n  <homepage>http://wine-hq.org</homepage>\n</Wine>")
            file.close()
        except:
            logger.error("Unable to write control.xml for "+version[1])
            print "Unable to write control.xml for "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/failed/"+filename)
            cleanup(cwd)
            continue
        
        os.chdir(cwd)
        
        logger.info("Creating package for "+version[1])
        print "Creating package for "+version[1]
        code = os.system("mv /tmp/build_wine ../incoming/wine-"+version[1])
        if code != 0:
            logger.error("Failed Creating package for "+version[1])
            print "Failed Creating package for "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/failed/"+filename)
            cleanup(cwd)
            continue
        else:
            logger.info("Creating package finished for "+version[1])
            print "Creating package finished for "+version[1]
            os.system("mv "+cwd+"/todo/"+filename+" "+cwd+"/done/"+filename)
            cleanup(cwd)
